package com.nikmesoft.android.referendumfriend.adapters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.MyGroupImage;
import com.nikmesoft.android.referendumfriend.models.item_activities;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;

public class activities_adapter extends ArrayAdapter<item_activities> {
	private int resourceID;
	TextView tv;
	private String[] names;
	public static int like = 0;
	public static int unlike = 0;
	public static int kt = 0;
	Context context;
	public WSLoader loader;
	private ProgressDialog dialog;
	ArrayList<String> idactivity = new ArrayList<String>();

	// ViewHolder holder;

	public activities_adapter(Context context, int resourceId,
			List<item_activities> objects,ArrayList<String> idactivity) {
		super(context, resourceId, objects);
		this.resourceID = resourceId;
		this.context = context;
		this.idactivity = idactivity;
		dialog = new ProgressDialog(context);
		dialog.setMessage("Loading...Please wait...");
	}

	static class ViewHolder {
		public TextView like, unlike;
		public TextView username;
		public TextView status_hobby;
		public ImageView imageLike, imageUnLike;

	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent){
		final item_activities status = getItem(position);
		View row = convertView;
		// if (row == null) {
		LayoutInflater inflater;
		inflater = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		row = inflater.inflate(this.resourceID, null);
		final ViewHolder viewHolder = new ViewHolder();
		viewHolder.like = (TextView) row.findViewById(R.id.like);
		viewHolder.unlike = (TextView) row.findViewById(R.id.unlike);
		viewHolder.imageLike = (ImageView) row.findViewById(R.id.imageLike);
		viewHolder.username = (TextView) row.findViewById(R.id.username);
		viewHolder.imageUnLike = (ImageView) row.findViewById(R.id.imageUnLike);
		viewHolder.status_hobby = (TextView) row.findViewById(R.id.statushobby);
		viewHolder.status_hobby.setTag(status);
		
		row.setTag(viewHolder);
		ViewHolder holder = (ViewHolder) row.getTag();
		// String s = names[position];
		holder.imageLike.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
			
				kt = 1;
				if (loader == null
						|| loader.isCancelled()
						|| loader.getStatus() == Status.FINISHED) {
					loader = new WSLoader();
					loader.execute(String.valueOf(LoginHandler.result.getId()),
							idactivity.get(position), "1");
				}
				like=Integer.parseInt(status.getLike());
				viewHolder.like.setText(String.valueOf(like+1));

			}

		});
		holder.imageUnLike.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				kt = 2;
				if (loader == null
						|| loader.isCancelled()
						|| loader.getStatus() == Status.FINISHED) {
					loader = new WSLoader();
					loader.execute(String.valueOf(LoginHandler.result.getId()),
							idactivity.get(position), "-1");
				}
				unlike=Integer.parseInt(status.getDislike());
				viewHolder.unlike.setText(String.valueOf(unlike+1));
			}

		});
		TextView nameuser = (TextView) row.findViewById(R.id.username);
		TextView like = (TextView) row.findViewById(R.id.like);
		TextView dislike = (TextView) row.findViewById(R.id.unlike);
		ImageView inavatar = (ImageView) row.findViewById(R.id.image_avatar);
		TextView statushobby = (TextView) row.findViewById(R.id.statushobby);
		if(position<MyGroupImage.ar_avatar.size())inavatar.setImageBitmap(MyGroupImage.ar_avatar.get(position));
		
		
		inavatar.setTag(status);
		like.setText(status.getLike());
		dislike.setText(status.getDislike());
		nameuser.setText(status.getUsername_user());
		statushobby.setText(status.getContent());
		return row;
	}

	private String callWS(String name1, String name2, String name3) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<addFB soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<AddFBRequest xsi:type=\"rdf:AddFBRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"
				+ name1
				+ "</id_user>"
				+ "<id_activity xsi:type=\"xsd:int\">"
				+ name2
				+ "</id_activity>"
				+ "<action xsi:type=\"xsd:int\">"
				+ name3
				+ "</action>"
				+ "</AddFBRequest>"
				+ "</addFB>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	public class WSLoader extends AsyncTask<String, Integer, String> {
		ViewHolder viewHolder = new ViewHolder();
		@Override
		protected String doInBackground(String... params) {
			return callWS(params[0], params[1], params[2]);

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);
			try {
				dialog.dismiss();
//				if (kt == 1) {
//					like++;
//					viewHolder.like.setText(String.valueOf(like));
//				} else {
//					unlike++;
//					viewHolder.unlike.setText(String.valueOf(unlike));
//				}
			} catch (Exception e) {
				dialog.dismiss();
			}

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
}
